#include <stdio.h>
#include <string.h>
#include "mqttpubsub.h"
#include "serialdrv.h"
char *g_reply_prefix;
char *g_sub_prefix;
void make_sub_topic(char *out, char const *prefix) {
	strcpy(out, prefix);
	//strcat(out, "/#");
}
void make_pub_topic(char *out, char const *prefix, char const *suffix) {
	strcpy(out, prefix);
	//strcat(out, suffix);
}
void recv_handler(char const *topic, char const *payload, int len) {
	char *out;
	int outlen;
	//static char pubtopic[256];
	//make_pub_topic(pubtopic, g_reply_prefix, topic + strlen(g_sub_prefix));
	//printf("from topic <%s>\n\trecv data <%.*s> \n\n", topic, len, payload);
	//out = shellexec(payload, len);//send to serial!
	// char pst[1024];
	// memset(pst,0,1024);
	// memcpy(payload,pst,strlen(payload));
	outlen=uart_sendstr((char *)payload);//
	//fprintf(stderr,"from topic %s,payload: %s to serial\n", topic,  payload);
	//fprintf(stderr,"---------------\n");
	//outlen = strlen(out);
	//mqtt_send(pubtopic, out, outlen);
}
int mmain(char *ip, int port, char *BDsub_topic, char *BDpub_topic,char *GPSpub_topic,char *ttySx,int btn) 
{
	//char subtopic[256];
	char pubbuf[1024];
	serial_init(ttySx,btn);
	//uart_sendstr("System started\r\n");
	fprintf(stderr,"BDsub_topic:%s\n", BDsub_topic);
	fprintf(stderr,"BDpub_topic:%s\n",BDpub_topic );
	fprintf(stderr,"GPSpub_topic:%s\n",GPSpub_topic);
	mqtt_setup(ip, port, BDsub_topic, recv_handler);
	for(;;)
	{
	    //fprintf(stderr,"--------------------\n" );
	    uart_readline(pubbuf);
	    if(strstr(pubbuf,"$BDTXR")>0||strstr(pubbuf,"$BDFKI")>0||strstr(pubbuf,"$CCTXA")>0||strstr(pubbuf,"$CCRMO")\
	        ||strstr(pubbuf,"$BDBSI"))
	    {
	    	//fprintf(stderr, "pub to topic%s\n", BDpub_topic);
	         	mqtt_send(BDpub_topic, pubbuf, strlen(pubbuf));
	    }
	    else
	    {
	    	//fprintf(stderr, "pub to topic%s\n", GPSpub_topic);
	    	mqtt_send(GPSpub_topic, pubbuf, strlen(pubbuf));
	    }  
	    usleep(20000);
	}
}

int main(int c, char **a) {
	if (c !=8 ) {
		fprintf(stderr, "usage: %s <ip> <port> <BDsubtopic> <BDpubtopic> <GPSpubtopic> <Com port> <Com baudrate>", a[0]);
		return 0;
	}
	mmain(a[1], atoi(a[2]), a[3], a[4],a[5],a[6],atoi(a[7]));
	return 0;
}

	
